import Cookie from 'js-cookie'
// 如果js-cookie下有红色线，鼠标移上去显示 找不到 js-cookie的声明文件
// cnpm i @types/js-cookie -S
// @types/*  *代表的就是各个模块的声明文件
// cnpm i @types/axios -S

export function setItem(key: string, value: string, days: number): void {
  if (window.localStorage) {
    localStorage.setItem(key, value)
  } else {
    Cookie.set(key, value, { expires: days })
  }
}

export function getItem(key: string): string | undefined {
  if (window.localStorage) {
    return localStorage.getItem(key) || ''
  } else {
    return Cookie.get(key)
  }
}

export function removeItem(key: string): void {
  if (window.localStorage) {
    localStorage.removeItem(key)
  } else {
    Cookie.set(key, '', { expires: -1 })
  }
}

export function clear(): void {
  if (window.localStorage) {
    localStorage.clear()
  } else {
    // 使用原生
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i];
      var eqPos = cookie.indexOf("=");
      var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
      document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    }
    if (cookies.length > 0) {
      for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        var domain = location.host.substr(location.host.indexOf('.'));
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=" + domain;
      }
    }
  }
}
